<template>
  <CollapsibleSection
    title="家族史"
    :is-expanded="isExpanded"
    @toggle="$emit('toggle')"
  >
    <!-- 表单 -->
    <div class="form-container">
      <p class="tip">系统性家族史记录，评估遗传与家族聚集风险</p>

      <form>
        <!-- 1. 家族性/遗传性疾病 -->
        <div class="section">
          <div class="section-title">
            <span class="section-number">1</span>
            <span>家族性/遗传性疾病</span>
          </div>

          <p class="section-desc">明确诊断的遗传病，如血友病、地中海贫血、亨廷顿舞蹈症、马凡综合征等</p>

          <div id="genetic-disease-container">
            <div class="disease-item" v-for="(disease, idx) in form.geneticDiseases" :key="disease.id">
              <button
                v-if="form.geneticDiseases.length > 1"
                type="button"
                class="remove-btn"
                @click="removeGeneticDisease(idx)"
              >
                删除
              </button>

              <div class="form-group">
                <label :for="`genetic-disease-${idx}`">遗传病名称</label>
                <input
                  :id="`genetic-disease-${idx}`"
                  class="form-input"
                  type="text"
                  v-model="disease.name"
                  placeholder="如：血友病、地中海贫血"
                />
              </div>

              <div class="form-group">
                <label>亲属关系</label>
                <div class="relative-options">
                  <div 
                    v-for="relativeOption in relativeOptions" 
                    :key="relativeOption.value"
                    class="checkbox-item" 
                    :class="{ 
                      'is-checked': hasRelative(disease, relativeOption.value),
                      'is-full-width': relativeOption.value === '其他'
                    }" 
                    @click="toggleRelative(disease, relativeOption.value)"
                  >
                    <input 
                      type="radio" 
                      :checked="hasRelative(disease, relativeOption.value)" 
                      :name="`relative-${disease.id}`"
                      tabindex="-1"
                    /> 
                    <span class="checkbox-label">{{ relativeOption.label }}</span>
                    <input
                      v-if="relativeOption.value === '其他' && hasRelative(disease, '其他')"
                      class="inline-input"
                      type="text"
                      v-model="disease.relativeOther"
                      placeholder="具体关系"
                      @click.stop
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>

          <button type="button" class="add-btn" @click="addGeneticDisease">添加遗传病记录</button>

          <div class="no-history">
            <div class="checkbox-item" :class="{ 'is-checked': form.noGeneticDisease }" @click="form.noGeneticDisease = !form.noGeneticDisease; onNoGeneticChange()">
              <input type="checkbox" :checked="form.noGeneticDisease" @change.stop /> 无家族性/遗传性疾病
            </div>
          </div>
        </div>

        <!-- 2. 常见多基因病 -->
        <div class="section">
          <div class="section-title">
            <span class="section-number">2</span>
            <span>常见多基因病</span>
          </div>

          <!-- 心血管疾病 -->
          <div class="form-group">
            <label>心血管疾病</label>
            <div class="checkbox-group">
              <div class="checkbox-item" :class="{ 'is-checked': form.polygenic.cardiovascular.diseases.includes('高血压') }" @click="toggleCheckbox(form.polygenic.cardiovascular.diseases, '高血压')">
                <input type="checkbox" :checked="form.polygenic.cardiovascular.diseases.includes('高血压')" @change.stop /> 高血压
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.polygenic.cardiovascular.diseases.includes('冠心病') }" @click="toggleCheckbox(form.polygenic.cardiovascular.diseases, '冠心病')">
                <input type="checkbox" :checked="form.polygenic.cardiovascular.diseases.includes('冠心病')" @change.stop /> 冠心病
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.polygenic.cardiovascular.diseases.includes('早发心梗') }" @click="toggleCheckbox(form.polygenic.cardiovascular.diseases, '早发心梗')">
                <input type="checkbox" :checked="form.polygenic.cardiovascular.diseases.includes('早发心梗')" @change.stop /> 早发心梗
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.polygenic.cardiovascular.diseases.includes('其他') }" @click="toggleCheckbox(form.polygenic.cardiovascular.diseases, '其他')">
                <input type="checkbox" :checked="form.polygenic.cardiovascular.diseases.includes('其他')" @change.stop />
                <span class="checkbox-label">其他</span>
                <input
                  v-if="form.polygenic.cardiovascular.diseases.includes('其他')"
                  class="inline-input"
                  type="text"
                  v-model="form.polygenic.cardiovascular.other"
                  placeholder="具体疾病"
                  @click.stop
                />
              </div>
            </div>

            <p class="early-onset-note">早发心梗定义：男性&lt;55岁，女性&lt;65岁</p>

            <div v-if="form.polygenic.cardiovascular.diseases.length > 0" class="details-section">
              <div class="form-group">
                <label for="cardiovascular-relatives">亲属关系与发病年龄</label>
                <textarea
                  id="cardiovascular-relatives"
                  class="form-input"
                  rows="2"
                  :value="form.polygenic.cardiovascular.details"
                  @input="(e: any) => handleTextareaInput('polygenic.cardiovascular.details', e)"
                  placeholder="记录：疾病、亲属关系、发病年龄（如'父亲于50岁时确诊心肌梗死'）"
                ></textarea>
              </div>
            </div>
          </div>

          <!-- 代谢性疾病 -->
          <div class="form-group">
            <label>代谢性疾病</label>
            <div class="checkbox-group">
              <div class="checkbox-item" :class="{ 'is-checked': form.polygenic.metabolic.diseases.includes('糖尿病') }" @click="toggleCheckbox(form.polygenic.metabolic.diseases, '糖尿病')">
                <input type="checkbox" :checked="form.polygenic.metabolic.diseases.includes('糖尿病')" @change.stop /> 糖尿病
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.polygenic.metabolic.diseases.includes('高脂血症') }" @click="toggleCheckbox(form.polygenic.metabolic.diseases, '高脂血症')">
                <input type="checkbox" :checked="form.polygenic.metabolic.diseases.includes('高脂血症')" @change.stop /> 高脂血症
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.polygenic.metabolic.diseases.includes('其他') }" @click="toggleCheckbox(form.polygenic.metabolic.diseases, '其他')">
                <input type="checkbox" :checked="form.polygenic.metabolic.diseases.includes('其他')" @change.stop />
                <span class="checkbox-label">其他</span>
                <input
                  v-if="form.polygenic.metabolic.diseases.includes('其他')"
                  class="inline-input"
                  type="text"
                  v-model="form.polygenic.metabolic.other"
                  placeholder="具体疾病"
                  @click.stop
                />
              </div>
            </div>

            <div v-if="form.polygenic.metabolic.diseases.length > 0" class="details-section">
              <div class="form-group">
                <label for="metabolic-relatives">亲属关系与发病年龄</label>
                <textarea
                  id="metabolic-relatives"
                  class="form-input"
                  rows="2"
                  :value="form.polygenic.metabolic.details"
                  @input="(e: any) => handleTextareaInput('polygenic.metabolic.details', e)"
                  placeholder="记录：疾病、亲属关系、发病年龄"
                ></textarea>
              </div>
            </div>
          </div>

          <!-- 肿瘤 -->
          <div class="form-group">
            <label>肿瘤</label>
            <p class="example-text">特别是直系亲属的恶性肿瘤史（如母亲/姐妹的乳腺癌、卵巢癌；家族的结直肠癌）</p>

            <div id="cancer-container">
              <div class="disease-item" v-for="(cancer, idx) in form.cancers" :key="cancer.id">
                <button
                  v-if="form.cancers.length > 1"
                  type="button"
                  class="remove-btn"
                  @click="removeCancer(idx)"
                >
                  删除
                </button>

                <div class="form-group">
                  <label :for="`cancer-type-${idx}`">肿瘤类型</label>
                  <input
                    :id="`cancer-type-${idx}`"
                    class="form-input"
                    type="text"
                    v-model="cancer.type"
                    placeholder="如：乳腺癌、结直肠癌"
                  />
                </div>

                <div class="form-group">
                  <label :for="`cancer-relative-${idx}`">亲属关系</label>
                  <select :id="`cancer-relative-${idx}`" class="form-input" v-model="cancer.relative">
                    <option value="">请选择</option>
                    <option value="父亲">父亲</option>
                    <option value="母亲">母亲</option>
                    <option value="兄弟">兄弟</option>
                    <option value="姐妹">姐妹</option>
                    <option value="儿子">儿子</option>
                    <option value="女儿">女儿</option>
                    <option value="祖父母">祖父母</option>
                    <option value="其他">其他</option>
                  </select>
                  <input
                    v-if="cancer.relative === '其他'"
                    class="inline-input"
                    type="text"
                    v-model="cancer.relativeOther"
                    placeholder="具体关系"
                  />
                </div>

                <div class="form-group">
                  <label :for="`cancer-age-${idx}`">发病年龄</label>
                  <input
                    :id="`cancer-age-${idx}`"
                    class="form-input"
                    type="number"
                    v-model.number="cancer.age"
                    placeholder="确诊时的年龄"
                  />
                </div>
              </div>
            </div>

            <button type="button" class="add-btn" @click="addCancer">添加肿瘤记录</button>
          </div>

          <!-- 精神神经疾病 -->
          <div class="form-group">
            <label>精神神经疾病</label>
            <div class="checkbox-group">
              <div class="checkbox-item" :class="{ 'is-checked': form.polygenic.neuro.diseases.includes('阿尔兹海默症') }" @click="toggleCheckbox(form.polygenic.neuro.diseases, '阿尔兹海默症')">
                <input type="checkbox" :checked="form.polygenic.neuro.diseases.includes('阿尔兹海默症')" @change.stop /> 阿尔兹海默症
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.polygenic.neuro.diseases.includes('精神分裂症') }" @click="toggleCheckbox(form.polygenic.neuro.diseases, '精神分裂症')">
                <input type="checkbox" :checked="form.polygenic.neuro.diseases.includes('精神分裂症')" @change.stop /> 精神分裂症
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.polygenic.neuro.diseases.includes('其他') }" @click="toggleCheckbox(form.polygenic.neuro.diseases, '其他')">
                <input type="checkbox" :checked="form.polygenic.neuro.diseases.includes('其他')" @change.stop /> 其他
                <input
                  v-if="form.polygenic.neuro.diseases.includes('其他')"
                  class="inline-input"
                  type="text"
                  v-model="form.polygenic.neuro.other"
                  placeholder="具体疾病"
                  @click.stop
                />
              </div>
            </div>

            <div v-if="form.polygenic.neuro.diseases.length > 0" class="details-section">
              <div class="form-group">
                <label for="neuro-relatives">亲属关系与发病年龄</label>
                <textarea
                  id="neuro-relatives"
                  class="form-input"
                  rows="2"
                  :value="form.polygenic.neuro.details"
                  @input="(e: any) => handleTextareaInput('polygenic.neuro.details', e)"
                  placeholder="记录：疾病、亲属关系、发病年龄"
                ></textarea>
              </div>
            </div>
          </div>

          <!-- 其他 -->
          <div class="form-group">
            <label>其他多基因病</label>
            <div class="checkbox-group">
              <div class="checkbox-item" :class="{ 'is-checked': form.polygenic.other.diseases.includes('自身免疫病') }" @click="toggleCheckbox(form.polygenic.other.diseases, '自身免疫病')">
                <input type="checkbox" :checked="form.polygenic.other.diseases.includes('自身免疫病')" @change.stop /> 自身免疫病
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.polygenic.other.diseases.includes('哮喘') }" @click="toggleCheckbox(form.polygenic.other.diseases, '哮喘')">
                <input type="checkbox" :checked="form.polygenic.other.diseases.includes('哮喘')" @change.stop /> 哮喘
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.polygenic.other.diseases.includes('其他') }" @click="toggleCheckbox(form.polygenic.other.diseases, '其他')">
                <input type="checkbox" :checked="form.polygenic.other.diseases.includes('其他')" @change.stop />
                <span class="checkbox-label">其他</span>
                <input
                  v-if="form.polygenic.other.diseases.includes('其他')"
                  class="inline-input"
                  type="text"
                  v-model="form.polygenic.other.other"
                  placeholder="具体疾病"
                  @click.stop
                />
              </div>
            </div>

            <div v-if="form.polygenic.other.diseases.length > 0" class="details-section">
              <div class="form-group">
                <label for="other-polygenic-relatives">亲属关系与发病年龄</label>
                <textarea
                  id="other-polygenic-relatives"
                  class="form-input"
                  rows="2"
                  :value="form.polygenic.other.details"
                  @input="(e: any) => handleTextareaInput('polygenic.other.details', e)"
                  placeholder="记录：疾病、亲属关系、发病年龄"
                ></textarea>
              </div>
            </div>
          </div>

          <div class="no-history">
            <div class="checkbox-item" :class="{ 'is-checked': form.noPolygenicDisease }" @click="form.noPolygenicDisease = !form.noPolygenicDisease; onNoPolygenicChange()">
              <input type="checkbox" :checked="form.noPolygenicDisease" @change.stop /> 无常见多基因病家族史
            </div>
          </div>
        </div>

        <!-- 3. 传染病 -->
        <div class="section">
          <div class="section-title">
            <span class="section-number">3</span>
            <span>传染病</span>
          </div>

          <p class="section-desc">如肺结核等，评估接触和易感风险</p>

          <div class="form-group">
            <label>传染病类型</label>
            <div class="checkbox-group">
              <div class="checkbox-item" :class="{ 'is-checked': form.infectious.diseases.includes('肺结核') }" @click="toggleCheckbox(form.infectious.diseases, '肺结核')">
                <input type="checkbox" :checked="form.infectious.diseases.includes('肺结核')" @change.stop /> 肺结核
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.infectious.diseases.includes('病毒性肝炎') }" @click="toggleCheckbox(form.infectious.diseases, '病毒性肝炎')">
                <input type="checkbox" :checked="form.infectious.diseases.includes('病毒性肝炎')" @change.stop /> 病毒性肝炎
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.infectious.diseases.includes('HIV/AIDS') }" @click="toggleCheckbox(form.infectious.diseases, 'HIV/AIDS')">
                <input type="checkbox" :checked="form.infectious.diseases.includes('HIV/AIDS')" @change.stop /> HIV/AIDS
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.infectious.diseases.includes('其他') }" @click="toggleCheckbox(form.infectious.diseases, '其他')">
                <input type="checkbox" :checked="form.infectious.diseases.includes('其他')" @change.stop /> 其他
                <input
                  v-if="form.infectious.diseases.includes('其他')"
                  class="inline-input"
                  type="text"
                  v-model="form.infectious.other"
                  placeholder="具体疾病"
                  @click.stop
                />
              </div>
            </div>
          </div>

          <div class="form-group">
            <label for="infectious-relatives">患病亲属与接触情况</label>
            <textarea
              id="infectious-relatives"
              class="form-input"
              rows="3"
              :value="form.infectious.details"
              @input="(e: any) => handleTextareaInput('infectious.details', e)"
              placeholder="记录：疾病、亲属关系、接触情况（如同住、密切接触等）"
            ></textarea>
          </div>

          <div class="no-history">
            <div class="checkbox-item" :class="{ 'is-checked': form.noInfectiousDisease }" @click="form.noInfectiousDisease = !form.noInfectiousDisease; onNoInfectiousChange()">
              <input type="checkbox" :checked="form.noInfectiousDisease" @change.stop /> 无传染病家族史
            </div>
          </div>
        </div>

        <div class="form-group">
          <div class="checkbox-item" :class="{ 'is-checked': form.confirmed }" @click="form.confirmed = !form.confirmed">
            <input type="checkbox" :checked="form.confirmed" @change.stop />
            确认信息无误，提交记录
          </div>
        </div>

        <button type="submit" class="submit-btn" @click="onSubmit" :disabled="!form.confirmed">提交记录</button>
      </form>
    </div>
  </CollapsibleSection>
</template>

<script setup lang="ts">
import CollapsibleSection from '@/components/CollapsibleSection.vue'
import { reactive, onMounted } from 'vue'
import Taro from '@tarojs/taro'

// 存储键名
const STORAGE_KEY = 'familyHistoryFormData'

interface Props {
  isExpanded: boolean
}

interface Emits {
  (e: 'toggle'): void
}

defineProps<Props>()
defineEmits<Emits>()

// 亲属关系选项
const relativeOptions = [
  { label: '父亲', value: '父亲' },
  { label: '母亲', value: '母亲' },
  { label: '兄弟', value: '兄弟' },
  { label: '姐妹', value: '姐妹' },
  { label: '儿子', value: '儿子' },
  { label: '女儿', value: '女儿' },
  { label: '其他', value: '其他' }
]

type GeneticDisease = {
  id: number
  name: string
  relative: string
  relativeOther: string
}

type Cancer = {
  id: number
  type: string
  relative: string
  relativeOther: string
  age: number | undefined
}

const form = reactive({
  geneticDiseases: [
    {
      id: 1,
      name: '',
      relative: '',
      relativeOther: ''
    } as GeneticDisease
  ],
  noGeneticDisease: false,
  polygenic: {
    cardiovascular: {
      diseases: [] as string[],
      other: '',
      details: ''
    },
    metabolic: {
      diseases: [] as string[],
      other: '',
      details: ''
    },
    neuro: {
      diseases: [] as string[],
      other: '',
      details: ''
    },
    other: {
      diseases: [] as string[],
      other: '',
      details: ''
    }
  },
  cancers: [
    {
      id: 1,
      type: '',
      relative: '',
      relativeOther: '',
      age: undefined
    } as Cancer
  ],
  noPolygenicDisease: false,
  infectious: {
    diseases: [] as string[],
    other: '',
    details: ''
  },
  noInfectiousDisease: false,
  confirmed: false
})

let geneticDiseaseIdCounter = 1
let cancerIdCounter = 1

function addGeneticDisease() {
  geneticDiseaseIdCounter += 1
  form.geneticDiseases.push({
    id: geneticDiseaseIdCounter,
    name: '',
    relative: '',
    relativeOther: ''
  })
}

function removeGeneticDisease(index: number) {
  form.geneticDiseases.splice(index, 1)
  if (form.geneticDiseases.length === 0) {
    addGeneticDisease()
  }
}

function onNoGeneticChange() {
  if (form.noGeneticDisease) {
    form.geneticDiseases = [
      {
        id: geneticDiseaseIdCounter + 1,
        name: '',
        relative: '',
        relativeOther: ''
      }
    ]
    geneticDiseaseIdCounter += 1
  }
}

function addCancer() {
  cancerIdCounter += 1
  form.cancers.push({
    id: cancerIdCounter,
    type: '',
    relative: '',
    relativeOther: '',
    age: undefined
  })
}

function removeCancer(index: number) {
  form.cancers.splice(index, 1)
  if (form.cancers.length === 0) {
    addCancer()
  }
}

function onNoPolygenicChange() {
  if (form.noPolygenicDisease) {
    form.polygenic.cardiovascular.diseases = []
    form.polygenic.cardiovascular.details = ''
    form.polygenic.metabolic.diseases = []
    form.polygenic.metabolic.details = ''
    form.polygenic.neuro.diseases = []
    form.polygenic.neuro.other = ''
    form.polygenic.neuro.details = ''
    form.polygenic.other.diseases = []
    form.polygenic.other.other = ''
    form.polygenic.other.details = ''
    form.cancers = [
      {
        id: cancerIdCounter + 1,
        type: '',
        relative: '',
        relativeOther: '',
        age: undefined
      }
    ]
    cancerIdCounter += 1
  }
}

function onNoInfectiousChange() {
  if (form.noInfectiousDisease) {
    form.infectious.diseases = []
    form.infectious.other = ''
    form.infectious.details = ''
  }
}

// 处理复选框点击（用于数组类型的复选框）
function toggleCheckbox(array: string[], value: string) {
  const index = array.indexOf(value)
  if (index > -1) {
    array.splice(index, 1)
  } else {
    array.push(value)
  }
}

// 检查是否选中某个亲属关系（单选）
function hasRelative(disease: GeneticDisease, value: string): boolean {
  return disease.relative === value
}

// 处理遗传病亲属关系单选点击
function toggleRelative(disease: GeneticDisease, value: string) {
  // 如果点击的是已选中的项，则清空；否则设置为新值
  if (disease.relative === value) {
    disease.relative = ''
    disease.relativeOther = ''
  } else {
    disease.relative = value
    // 如果不是"其他"，清空其他输入框
    if (value !== '其他') {
      disease.relativeOther = ''
    }
  }
}

// 处理 textarea 输入事件（兼容 Taro 和 Web 环境）
function handleTextareaInput(field: string, e: any) {
  const value = e?.detail?.value ?? e?.target?.value ?? e?.detail ?? ''
  console.log(`📝 textarea [${field}] 输入事件:`, { value })
  
  // 根据字段路径更新数据
  const fieldParts = field.split('.')
  
  // 处理三部分路径：polygenic.cardiovascular.details 等
  if (fieldParts.length === 3) {
    const [obj, subObj, key] = fieldParts
    if (obj === 'polygenic') {
      if (subObj === 'cardiovascular' && key === 'details') form.polygenic.cardiovascular.details = value
      else if (subObj === 'metabolic' && key === 'details') form.polygenic.metabolic.details = value
      else if (subObj === 'neuro' && key === 'details') form.polygenic.neuro.details = value
      else if (subObj === 'other' && key === 'details') form.polygenic.other.details = value
    }
  }
  // 处理两部分路径：infectious.details
  else if (fieldParts.length === 2) {
    const [obj, key] = fieldParts
    if (obj === 'infectious' && key === 'details') {
      form.infectious.details = value
    }
  }
  
  console.log(`✅ textarea [${field}] 已更新为:`, value)
}

// 深拷贝函数
function deepClone<T>(obj: T): T {
  return JSON.parse(JSON.stringify(obj))
}

// 保存表单数据到缓存
function saveFormData() {
  try {
    const formDataCopy = deepClone(form)
    Taro.setStorageSync(STORAGE_KEY, formDataCopy)
    console.log('✅ 家族史表单数据已保存到缓存')
  } catch (error: any) {
    console.error('❌ 保存表单数据失败:', error)
    Taro.showToast({
      title: '保存数据失败',
      icon: 'none',
      duration: 2000
    })
  }
}

// 从缓存读取表单数据
function loadFormData() {
  try {
    const savedData = Taro.getStorageSync(STORAGE_KEY)
    if (savedData) {
      const parsedData = typeof savedData === 'string' ? JSON.parse(savedData) : savedData
      if (parsedData && typeof parsedData === 'object') {
        // 深度合并数据
        if (parsedData.geneticDiseases && Array.isArray(parsedData.geneticDiseases)) {
          // 兼容旧数据格式（relatives 数组）和新格式（relative 字符串）
          form.geneticDiseases = parsedData.geneticDiseases.map((disease: any) => {
            // 如果旧数据是数组格式，取第一个值；否则使用新格式
            let relative = ''
            if (Array.isArray(disease.relatives) && disease.relatives.length > 0) {
              relative = disease.relatives[0]
            } else if (typeof disease.relative === 'string') {
              relative = disease.relative
            }
            return {
              ...disease,
              relative: relative,
              relativeOther: disease.relativeOther || ''
            }
          })
        }
        if (parsedData.noGeneticDisease !== undefined) form.noGeneticDisease = parsedData.noGeneticDisease
        if (parsedData.polygenic) Object.assign(form.polygenic, parsedData.polygenic)
        if (parsedData.cancers && Array.isArray(parsedData.cancers)) form.cancers = parsedData.cancers
        if (parsedData.noPolygenicDisease !== undefined) form.noPolygenicDisease = parsedData.noPolygenicDisease
        if (parsedData.infectious) Object.assign(form.infectious, parsedData.infectious)
        if (parsedData.noInfectiousDisease !== undefined) form.noInfectiousDisease = parsedData.noInfectiousDisease
        if (parsedData.confirmed !== undefined) form.confirmed = parsedData.confirmed
        
        console.log('✅ 家族史表单数据已从缓存加载')
      }
    }
  } catch (error: any) {
    console.error('❌ 加载表单数据失败:', error)
  }
}

// 组件挂载时加载缓存数据
onMounted(() => {
  loadFormData()
})

function onSubmit() {
  // 保存数据到缓存
  saveFormData()
  
  // 这里可替换为真实提交逻辑
  Taro.showToast({
    title: '家族史记录提交成功！',
    icon: 'success',
    duration: 2000
  })
}
</script>

<style scoped>
.form-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  padding: 18px;
}
.tip { 
  text-align: center; 
  margin-bottom: 20px; 
  color: #666; 
  font-size: 20px; 
  line-height: 1.6; 
}
.section { 
  margin-bottom: 26px; 
  padding-bottom: 20px; 
  border-bottom: 1px dashed #eee; 
}
.section-title { 
  display: flex; 
  align-items: center; 
  margin-bottom: 16px; 
  font-weight: 600; 
  font-size: 22px; 
  color: #333;
}
.section-number { 
  display: inline-flex; 
  align-items: center; 
  justify-content: center; 
  width: 32px; 
  height: 32px; 
  background-color: #2c80ff; 
  color: #fff; 
  border-radius: 50%; 
  margin-right: 10px; 
  font-size: 16px; 
  font-weight: 600;
}
.section-desc { 
  margin-bottom: 12px; 
  color: #666; 
  font-size: 18px; 
  line-height: 1.6;
}
.form-group { margin-bottom: 24px; }
label { 
  display: block; 
  margin-bottom: 12px; 
  font-weight: 600; 
  font-size: 20px; 
  color: #333; 
  line-height: 1.5; 
}

/* 所有输入框统一样式 - 优化字体、背景和边框 */
.form-input,
input[type='text'],
input[type='number'],
select,
textarea {
  width: 100%;
  padding: 22px 26px;
  border: 2px solid #d0d7de;
  border-radius: 12px;
  font-size: 24px !important;
  background-color: #f8f9fa !important;
  color: #333 !important;
  box-sizing: border-box;
  -webkit-appearance: none;
  appearance: none;
  line-height: 1.7;
  min-height: 64px;
  transition: all 0.3s ease;
  font-weight: 500;
  display: block;
}

.form-input:hover,
input[type='text']:hover,
input[type='number']:hover,
select:hover,
textarea:hover {
  border-color: #b0b7c0 !important;
  background-color: #f0f1f3 !important;
}

.form-input:focus,
input:focus,
input[type='text']:focus,
input[type='number']:focus,
select:focus,
textarea:focus {
  border-color: #2c80ff !important;
  background-color: #fff !important;
  outline: none;
  box-shadow: 0 0 0 4px rgba(44, 128, 255, 0.15) !important;
  transform: translateY(-1px);
}

textarea.form-input,
textarea {
  min-height: 150px;
  resize: vertical;
  font-family: inherit;
  font-size: 24px !important;
  line-height: 1.7;
  padding: 22px 26px;
  background-color: #f8f9fa !important;
  border: 2px solid #d0d7de;
  border-radius: 12px;
  transition: all 0.3s ease;
  font-weight: 500;
}
.checkbox-group { 
  display: flex; 
  flex-direction: column; 
  gap: 16px; 
  margin-top: 10px; 
}
.checkbox-item { 
  display: flex; 
  align-items: center; 
  gap: 12px; 
  padding: 18px 16px; 
  background: #f9f9f9; 
  border-radius: 8px; 
  min-height: 60px;
  font-size: 20px;
  transition: all 0.2s ease;
  border: 2px solid #e9ecef;
  cursor: pointer;
  position: relative;
  flex-wrap: nowrap;
}

.checkbox-item:active { 
  background-color: #f0f0f0; 
}

/* 选中状态样式 */
.checkbox-item:has(input:checked),
.checkbox-item.is-checked {
  background-color: #e7f3ff !important;
  border-color: #2c80ff !important;
  border-width: 2px !important;
  box-shadow: 0 2px 8px rgba(44, 128, 255, 0.15);
}

.checkbox-item input[type="checkbox"],
.checkbox-item input[type="radio"] {
  width: 24px;
  height: 24px;
  min-width: 24px;
  min-height: 24px;
  cursor: pointer;
  accent-color: #2c80ff;
  flex-shrink: 0;
  margin: 0;
  pointer-events: none;
}

.checkbox-item input[type="checkbox"]:checked,
.checkbox-item input[type="radio"]:checked {
  accent-color: #2c80ff;
}

/* checkbox 标签样式 - 不换行 */
.checkbox-label {
  white-space: nowrap;
  flex-shrink: 0;
}

.checkbox-item .inline-input {
  flex: 1;
  min-width: 0;
}

/* 选中时文字颜色和字重 - 针对 label 内的文本 */
.checkbox-item:has(input:checked),
.checkbox-item.is-checked {
  color: #2c80ff;
  font-weight: 600;
}

/* 确保选中时整个 checkbox-item 的文字都变色 */
.checkbox-item:has(input:checked) *,
.checkbox-item.is-checked * {
  color: #2c80ff;
  font-weight: 600;
}

/* 但保持 input 本身的样式 */
.checkbox-item:has(input:checked) input,
.checkbox-item.is-checked input {
  color: initial;
  font-weight: initial;
}

/* "其他"选项占满一行 */
.checkbox-item.is-full-width {
  grid-column: 1 / -1;
}

/* NutUI 组件样式统一 */
:deep(.nut-input) {
  font-size: 24px !important;
  background-color: #f8f9fa !important;
  border: 2px solid #d0d7de !important;
  border-radius: 12px !important;
  min-height: 64px !important;
  padding: 22px 26px !important;
}

:deep(.nut-input:focus) {
  border-color: #2c80ff !important;
  background-color: #fff !important;
  box-shadow: 0 0 0 4px rgba(44, 128, 255, 0.15) !important;
}

:deep(.nut-button) {
  font-size: 20px !important;
  min-height: 60px !important;
  font-weight: 600 !important;
  border-radius: 8px !important;
}

.inline-input { 
  flex: 1;
  /* min-width: 120px;
  max-width: 300px; */
  margin-left: 8px;
  padding: 8px 12px; 
  font-size: 20px !important; 
  height: 36px;
  /* line-height: 24px; */
  border: 2px solid #d0d7de;
  border-radius: 8px;
  background-color: #fff !important;
  transition: all 0.2s ease;
  box-sizing: border-box;
}

.inline-input:focus {
  border-color: #2c80ff !important;
  background-color: #fff !important;
  outline: none;
  box-shadow: 0 0 0 3px rgba(44, 128, 255, 0.1);
}
.relative-options { 
  display: grid; 
  grid-template-columns: repeat(2, 1fr); 
  gap: 12px; 
  margin-top: 8px; 
}
.add-btn { 
  background: #2c80ff; 
  color: #fff; 
  border: none; 
  border-radius: 8px; 
  padding: 18px 24px; 
  font-size: 20px; 
  cursor: pointer; 
  margin-top: 16px; 
  width: 100%; 
  min-height: 60px; 
  font-weight: 600;
  transition: all 0.2s ease;
  box-shadow: 0 2px 8px rgba(44, 128, 255, 0.2);
}
.add-btn:active { background: #1a6fe0; }
.remove-btn { 
  background: #ff4757; 
  color: #fff; 
  border: none; 
  border-radius: 8px; 
  padding: 16px 20px; 
  font-size: 18px; 
  cursor: pointer; 
  margin-bottom: 16px; 
  width: 100%; 
  min-height: 56px; 
  font-weight: 600;
  transition: all 0.2s ease;
  box-shadow: 0 2px 8px rgba(255, 71, 87, 0.2);
}
.remove-btn:active { background-color: #e63946; }
.disease-item { 
  background: #f9f9f9; 
  padding: 20px; 
  border-radius: 8px; 
  margin-bottom: 20px; 
  position: relative;
  border: 2px solid #e9ecef;
}
.details-section { 
  margin-top: 12px; 
  padding-top: 12px; 
  border-top: 1px dashed #eee; 
}
.submit-btn { 
  background: #2c80ff; 
  color: #fff; 
  border: none; 
  border-radius: 8px; 
  padding: 18px 24px; 
  font-size: 20px; 
  cursor: pointer; 
  width: 100%; 
  min-height: 60px; 
  margin-top: 20px;
  font-weight: 600;
  transition: all 0.2s ease;
  box-shadow: 0 4px 12px rgba(44, 128, 255, 0.3);
}
.submit-btn:active:not(:disabled) { background: #1a6fe0; }
.submit-btn:disabled { opacity: 0.6; cursor: not-allowed; }
.example-text { 
  font-size: 16px; 
  color: #888; 
  margin-top: 6px; 
  margin-bottom: 10px; 
  line-height: 1.5;
}
.early-onset-note { 
  font-size: 16px; 
  color: #ff4757; 
  margin-top: 6px; 
  margin-bottom: 10px; 
  line-height: 1.5;
}
.no-history { 
  color: #888; 
  font-style: italic; 
  margin: 16px 0; 
  font-size: 18px;
}
.form-container { padding: 24rpx; }
.tip { margin-bottom: 24rpx; font-size: 26rpx; }
.section { margin-bottom: 28rpx; padding-bottom: 24rpx; }
.section-title { margin-bottom: 20rpx; font-size: 30rpx; }
.section-number { width: 44rpx; height: 44rpx; margin-right: 12rpx; font-size: 24rpx; }
.form-group { margin-bottom: 24rpx; }
label { margin-bottom: 12rpx; font-size: 28rpx; }
.form-input,
input[type='text'],
input[type='number'],
select,
textarea { padding: 24rpx 24rpx; border-width: 2rpx; font-size: 28rpx !important; min-height: 72rpx; }
textarea.form-input, textarea { min-height: 150rpx; font-size: 28rpx !important; padding: 24rpx 24rpx; border-width: 2rpx; }
.checkbox-group { gap: 16rpx; }
.checkbox-item { padding: 20rpx 16rpx; min-height: 64rpx; font-size: 28rpx; border-width: 2rpx; }
.checkbox-item input[type="checkbox"], .checkbox-item input[type="radio"] { width: 28rpx; height: 28rpx; min-width: 28rpx; min-height: 28rpx; }
.date-display { padding: 24rpx 24rpx; border-width: 2rpx; min-height: 72rpx; font-size: 28rpx !important; }
.inline-input { margin-top: 12rpx; padding: 16rpx 20rpx; font-size: 28rpx !important; border-width: 2rpx; }
</style>


